interface IHistoryRecord {
  content: string;
  size: number;
  errorLevel: string;
  fgColor: string;
  bgColor: string;
  imagePath: string;
  timestamp: number;
}

Component({
  data: {
    historyList: [] as IHistoryRecord[],
    statusBarHeight: 20,
    navBarHeight: 64
  },

  lifetimes: {
    attached() {
      // 获取状态栏高度
      const systemInfo = wx.getSystemInfoSync();
      const statusBarHeight = systemInfo.statusBarHeight || 20;

      this.setData({
        statusBarHeight: statusBarHeight,
        navBarHeight: statusBarHeight + 44, // 44是导航栏的高度
        historyList: []
      });

      this.loadHistory();
    }
  },

  pageLifetimes: {
    show() {
      // 每次页面显示时重新加载历史记录
      this.loadHistory();
    }
  },

  methods: {
    // 返回上一页
    goBack() {
      wx.navigateBack({
        delta: 1
      });
    },

    // 加载历史记录
    loadHistory() {
      const history = wx.getStorageSync('qrHistory') || [];
      this.setData({ historyList: history });
    },

    // 点击记录项
    onRecordTap(e: WechatMiniprogram.Touch) {
      const index = e.currentTarget.dataset.index;
      const record = this.data.historyList[index];
      
      // 跳转到首页并传递参数
      wx.navigateTo({
        url: `/pages/index/index?record=${JSON.stringify(record)}`
      });
    },

    // 预览图片
    previewImage(e: WechatMiniprogram.Touch) {
      const index = e.currentTarget.dataset.index;
      const record = this.data.historyList[index];
      
      wx.previewImage({
        current: record.imagePath,
        urls: [record.imagePath]
      });
    },

    // 删除记录
    deleteRecord(e: WechatMiniprogram.Touch) {
      const index = e.currentTarget.dataset.index;
      
      wx.showModal({
        title: '提示',
        content: '确定要删除这条记录吗？',
        success: (res) => {
          if (res.confirm) {
            const history = [...this.data.historyList];
            history.splice(index, 1);
            wx.setStorageSync('qrHistory', history);
            this.setData({ historyList: history });
            
            wx.showToast({
              title: '已删除',
              icon: 'success'
            });
          }
        }
      });
    },

    // 清空历史记录
    clearHistory() {
      wx.showModal({
        title: '提示',
        content: '确定要清空所有历史记录吗？',
        success: (res) => {
          if (res.confirm) {
            wx.removeStorageSync('qrHistory');
            this.setData({ historyList: [] });
            
            wx.showToast({
              title: '已清空',
              icon: 'success'
            });
          }
        }
      });
    }
  }
});